package com.hiv.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.LinkedHashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;

/**
 * Bean 工具类
 */
@Slf4j
public final class BeanUtil {
    
    private BeanUtil() {

    }

    /**
     *
     * @param clzz
     * @param fields
     * @return
     */
    private static Field[] getAllFields(Class clzz, Field[] fields) {
        if (clzz != Object.class) {
            Field[] newFields = ArrayUtils.addAll(fields,
                    clzz.getDeclaredFields());
            return getAllFields(clzz.getSuperclass(), newFields);
        }
        return fields;
    }

    /**
     * Bean转换为Map格式
     *
     * @param bean
     * @return
     */
    @SuppressWarnings("all")
    public static Map<String, Object> toMap(Object bean) {
        if (bean == null) {
            return null;
        }
        if (Map.class.isAssignableFrom(bean.getClass())) {
            return (Map<String, Object>) bean;
        }
        Field[] fields = getAllFields(bean.getClass(), new Field[0]);
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                if (!Modifier.isStatic(field.getModifiers())) {
                    map.put(field.getName(), field.get(bean));
                }
            }
        } catch (Exception e) {
            log.error("exception:", e);
        }
        return map;
    }

}